#include<iostream>
using namespace std;
struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
 };
 
class Solution {
public:
    TreeNode*find(TreeNode* root)
    {
        if(!root->left)return root;

        return find(root->left);
    }
    TreeNode* deleteNode(TreeNode* root, int key) {
        //find
        if(root==NULL)return NULL;
        if(root->val==key)
        {
            //delete
            if(!root->left&&!root->right)
            {
                return NULL;
            }
            else if(!root->left)
            {
                return root->right;
            }
            else if(!root->right)
                return root->left;
            TreeNode *tmp=find(root->right);
            root->val=tmp->val;
            root->right=deleteNode(root->right,tmp->val);
        }
        else if(root->val<key)root->right=deleteNode(root->right, key);
        else if(root->val>key)root->left=deleteNode(root->left, key);
        return root;
    }
};